/**
 * Copyright &copy; 2012-2016 <a href="https://www.kaaction.com">KAA</a> All rights reserved All rights reserved.
 */
package com.kaaction.modules.ka.web;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.DateUtils;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.utils.excel.ExportExcel;
import com.kaaction.modules.ka.entity.KaFinance;
import com.kaaction.modules.ka.service.KaFinanceService;
import com.kaaction.modules.sys.entity.User;

/**
 * 财务报表Controller
 * @author ZengBiao
 * @version 2017-06-23
 */
@Controller
@RequestMapping(value = "${adminPath}/ka/kaFinance")
public class KaFinanceController extends BaseController {

	@Autowired
	private KaFinanceService kaFinanceService;
	
	@ModelAttribute
	public KaFinance get(@RequestParam(required=false) String id) {
		KaFinance entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = kaFinanceService.get(id);
		}
		if (entity == null){
			entity = new KaFinance();
		}
		return entity;
	}
	
	@RequiresPermissions("ka:kaFinance:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(KaFinance kaFinance, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "KAA-"+kaFinance.getYear()+"-"+kaFinance.getMonth()+".xlsx";
            List<KaFinance> kaFinanceList = kaFinanceService.findList(kaFinance);
            
            KaFinance summary = new KaFinance();
            double beginNumTotal = 0.0;
			double beginCostTotal = 0.0;
			double checkInNumTotal = 0.0;
			double checkInCostTotal = 0.0;
			double checkoutNumTotal = 0.0;
			double checkoutCostTotal = 0.0;
			double endNumTotal = 0.0;
			double endCostTotal = 0.0;
			double badNumTotal = 0.0;
			
            for(int i=0;i<kaFinanceList.size();i++){
				KaFinance ins = kaFinanceList.get(i);
				if(ins != null){
					beginNumTotal += ins.getBeginNum();
					beginCostTotal += ins.getBeginCost();
					
					checkInNumTotal += ins.getCheckinNum();
					checkInCostTotal += ins.getCheckinCost();
					
					checkoutNumTotal += ins.getCheckoutNum();
					checkoutCostTotal += ins.getCheckoutCost();
					
					endNumTotal += ins.getEndNum();
					endCostTotal += ins.getEndCost();
					
					badNumTotal += ins.getBadNum();
				}
			}
            summary.setCode("统计");
            summary.setBeginNum(beginNumTotal);
            summary.setBeginCost(beginCostTotal);
            summary.setBeginPrice(beginCostTotal/beginNumTotal);
            
            summary.setCheckinNum(checkInNumTotal);
            summary.setCheckinPrice(checkInCostTotal/checkInNumTotal);
            summary.setCheckinCost(checkInCostTotal);
            
            summary.setCheckoutNum(checkoutNumTotal);
            summary.setBadNum(badNumTotal);
            summary.setCheckoutCost(checkoutCostTotal);;
            summary.setCheckoutPrice(checkoutCostTotal/checkoutNumTotal);;
            
            summary.setEndNum(endNumTotal);
            summary.setEndCost(endCostTotal);
            summary.setEndPrice(endCostTotal/endNumTotal);
            kaFinanceList.add(summary);
    		new ExportExcel("财务报表~"+kaFinance.getYear()+"-"+kaFinance.getMonth(), KaFinance.class).setDataList(kaFinanceList).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出财务报表失败！失败信息："+e.getMessage());
		}
		String yearStr = kaFinance.getYear();
		int year = 117;
		if(!StringUtils.isBlank(yearStr))year = Integer.parseInt(yearStr) - 1900;
		return "redirect:"+Global.getAdminPath()+"/ka/kaFinance/?repage&year="+year+"&month="+kaFinance.getMonth();
    }
	
	@RequiresPermissions("ka:kaFinance:view")
	@RequestMapping(value = {"list", ""})
	public String list(KaFinance kaFinance,KaFinance kaFinanceIns, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		String yearStr = request.getParameter("year");
		String monthStr = request.getParameter("month");
		int year = 0;
		int month = 0;
		if(!StringUtils.isBlank(yearStr)){
			year = Integer.parseInt(yearStr);
			kaFinance.setYear(String.valueOf(year));
		}
		if(!StringUtils.isBlank(monthStr)){
			month = Integer.parseInt(monthStr);
			kaFinance.setMonth(String.valueOf(month));
		}
		logger.info("year=" + year);
		logger.info("month=" + month);
		if(kaFinance.getYear() != null && kaFinance.getYear() .compareTo("2016") > 0){
			Page<KaFinance> page = kaFinanceService.findPage(new Page<KaFinance>(request, response), kaFinance); 
			model.addAttribute("page", page);
			double beginNumTotal = 0.0;
			double beginCostTotal = 0.0;
			double checkInNumTotal = 0.0;
			double checkInCostTotal = 0.0;
			double checkoutNumTotal = 0.0;
			double checkoutCostTotal = 0.0;
			double endNumTotal = 0.0;
			double endCostTotal = 0.0;
			double badNumTotal = 0.0;
			
			List<KaFinance> kaFinanceList = kaFinanceService.findAllListByMonth(kaFinance.getYear(),kaFinance.getMonth());
			
			for(int i=0;i<kaFinanceList.size();i++){
				KaFinance ins = kaFinanceList.get(i);
				if(ins != null){
					beginNumTotal += ins.getBeginNum();
					beginCostTotal += ins.getBeginCost();
					
					checkInNumTotal += ins.getCheckinNum();
					checkInCostTotal += ins.getCheckinCost();
					
					checkoutNumTotal += ins.getCheckoutNum();
					checkoutCostTotal += ins.getCheckoutCost();
					
					endNumTotal += ins.getEndNum();
					endCostTotal += ins.getEndCost();
					badNumTotal += ins.getBadNum();
				}
			}
			model.addAttribute("beginNumTotal", beginNumTotal);
			model.addAttribute("beginCostTotal", beginCostTotal);
			model.addAttribute("checkInNumTotal", checkInNumTotal);
			model.addAttribute("checkInCostTotal", checkInCostTotal);
			model.addAttribute("checkoutNumTotal", checkoutNumTotal);
			model.addAttribute("checkoutCostTotal", checkoutCostTotal);
			model.addAttribute("endNumTotal", endNumTotal);
			model.addAttribute("endCostTotal", endCostTotal);
			model.addAttribute("badNumTotal", badNumTotal);
			
		}
		
		return "modules/ka/kaFinanceList";
	}

	@RequiresPermissions("ka:kaFinance:view")
	@RequestMapping(value = "form")
	public String form(KaFinance kaFinance, Model model) {
		model.addAttribute("kaFinance", kaFinance);
		return "modules/ka/kaFinanceForm";
	}

	@RequiresPermissions("ka:kaFinance:edit")
	@RequestMapping(value = "save")
	public String save(KaFinance kaFinance, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, kaFinance)){
			return form(kaFinance, model);
		}
		kaFinanceService.save(kaFinance);
		addMessage(redirectAttributes, "保存财务报表成功");
		return "redirect:"+Global.getAdminPath()+"/ka/kaFinance/?repage";
	}
	
	@RequiresPermissions("ka:kaFinance:edit")
	@RequestMapping(value = "delete")
	public String delete(KaFinance kaFinance, RedirectAttributes redirectAttributes) {
		kaFinanceService.delete(kaFinance);
		addMessage(redirectAttributes, "删除财务报表成功");
		return "redirect:"+Global.getAdminPath()+"/ka/kaFinance/?repage";
	}
	
	@RequiresPermissions("ka:kaFinance:edit")
	@RequestMapping(value = "report")
	public String report(KaFinance kaFinanceIns,RedirectAttributes redirectAttributes) {
		Date beginDate = new Date();
		int yearInt = 117;
		int monthInt = 0;
		if(kaFinanceIns != null && !StringUtils.isBlank(kaFinanceIns.getYear()) && !StringUtils.isBlank(kaFinanceIns.getMonth())) {
			yearInt = Integer.parseInt(kaFinanceIns.getYear()) - 1900;
			monthInt = Integer.parseInt(kaFinanceIns.getMonth());
		}
		
		beginDate.setYear(yearInt);
		beginDate.setMonth(monthInt);
		kaFinanceService.summarize(beginDate);
		addMessage(redirectAttributes, "重新计算财务报表成功");
		return "redirect:"+Global.getAdminPath()+"/ka/kaFinance/?repage&year="+kaFinanceIns.getYear()+"&month="+monthInt;
	}

}